/**
 * 获取url中参数的值
 * 事例：?masterId=123，输入url, masterId，返回123
 */
function getParams (url, key) {
  url = url || window.location.href
  let reg = new RegExp(key + '\=([^\&]+)')
  if (decodeURIComponent(url).match(reg)) {
    return RegExp.$1
  }
  return ''
}

/**
 * 获取url中所有参数的值
 * 事例：?type=mat&masterId=123，输入key，返回对象{ type: 'mat', masterId: 123 }
 */
function getAllParams (url) {
  url = url || window.location.href
  let searchString = decodeURIComponent(url.substring(url.indexOf('?') + 1))
  let searchArray = searchString.split('&')
  let result = {}
  for (let i = 0; i < searchArray.length; i++) {
    let keyValue = searchArray[i].split('=')
    if (keyValue.length === 2) {
      result[keyValue[0]] = keyValue[1]
    }
  }
  return result
}

/**
 * 格式化对象为url字符串
 * 事例：mat&masterId=123
 */
function parseParams (obj) {
  let paramsStr = ''
  for (let i in obj) {
    paramsStr += (paramsStr ? '&' : '') + i + '=' + obj[i]
  }
  return paramsStr
}

export {
  getParams,
  getAllParams,
  parseParams
}
